from rest_framework import status, generics
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenRefreshView
from django.contrib.auth import login
from ..models import CustomUser, Institution, Laboratory
from .serializers import (
    LoginSerializer, UserSerializer, 
    InstitutionSerializer, LaboratorySerializer
)


@api_view(['POST'])
@permission_classes([AllowAny])
def check_user_type_view(request):
    """检查用户邮箱对应的账户类型"""
    email = request.data.get('email')
    if not email:
        return Response({'error': '请提供邮箱地址'}, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        user = CustomUser.objects.get(email=email, is_active=True)
        return Response({
            'user_type': user.user_type,
            'full_name': user.full_name,
            'institution_name': user.institution.name if user.institution else None,
            'laboratory_name': user.laboratory.name if user.laboratory else None
        })
    except CustomUser.DoesNotExist:
        return Response({'error': '用户不存在或账户已被禁用'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['POST'])
@permission_classes([AllowAny])
def login_view(request):
    """用户登录"""
    serializer = LoginSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.validated_data['user']
        refresh = RefreshToken.for_user(user)
        
        return Response({
            'message': '登录成功',
            'user': UserSerializer(user).data,
            'tokens': {
                'access': str(refresh.access_token),
                'refresh': str(refresh)
            }
        })
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout_view(request):
    """用户登出"""
    try:
        refresh_token = request.data.get('refresh')
        if refresh_token:
            token = RefreshToken(refresh_token)
            token.blacklist()
        return Response({'message': '登出成功'})
    except Exception:
        return Response({'error': '登出失败'}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def profile_view(request):
    """获取用户信息"""
    serializer = UserSerializer(request.user)
    return Response(serializer.data)


class InstitutionListView(generics.ListAPIView):
    """机构列表"""
    queryset = Institution.objects.all()
    serializer_class = InstitutionSerializer
    permission_classes = [AllowAny]


class LaboratoryListView(generics.ListAPIView):
    """实验室列表"""
    queryset = Laboratory.objects.all()
    serializer_class = LaboratorySerializer
    permission_classes = [AllowAny]
    
    def get_queryset(self):
        queryset = super().get_queryset()
        institution = self.request.query_params.get('institution', None)
        if institution:
            queryset = queryset.filter(institution__code=institution)
        return queryset


class CustomTokenRefreshView(TokenRefreshView):
    """自定义Token刷新视图"""
    pass